﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControls_CarbonFootprintQuestion_Energy_Heating : CarbonExchange.WebControls.AuditQuestionBase
{
    private string InsulationChoiceName;
    private List<string> RenewableChoices = new List<string>();
    private string RenewableChoiceName;

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        rdoHeatingElectric.SelectedIndexChanged += new EventHandler(rdoHeatingElectric_SelectedIndexChanged);
        rdoHeatingBills.SelectedIndexChanged += new EventHandler(rdoHeatingBills_SelectedIndexChanged);
        ameeHeatingEstimate.LabelDataBound += new EventHandler<CarbonExchange.WebControls.AmeeDrillDown.LabelDataBindingEventArgs>(ameeHeatingEstimate_LabelDataBound);
        ameeHeatingEstimate.DropDownDataBinding += new EventHandler<CarbonExchange.WebControls.AmeeDrillDown.DropDownDataBindingEventArgs>(ameeHeatingEstimate_DropDownDataBinding);
        dsRenewable.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsRenewable_Select);
        rptRenewable.ItemDataBound += new EventHandler<Acms.WebControls.ItemDataBoundEventArgs>(rptRenewable_ItemDataBound);
        dsInsulation.Select += new EventHandler<Acms.DataControls.EventDrivenDataSourceSelectEventArgs>(dsInsulation_Select);
        cblInsulation.DataBound += new EventHandler(cblInsulation_DataBound);
        ameeHeatingType.LabelDataBound += new EventHandler<CarbonExchange.WebControls.AmeeDrillDown.LabelDataBindingEventArgs>(ameeHeatingType_LabelDataBound);
        ameeHeatingType.DropDownDataBinding += new EventHandler<CarbonExchange.WebControls.AmeeDrillDown.DropDownDataBindingEventArgs>(ameeHeatingType_DropDownDataBinding);
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    void rdoHeatingElectric_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (rdoHeatingElectric.SelectedValue != "0")
        {
            pnlHeatingBills.Visible = false;
            phHeatingBills.Visible = false;
            phHeatingEstimate.Visible = false;
        }
        else
        {
            pnlHeatingBills.Visible = true;
            phHeatingBills.Visible = rdoHeatingBills.SelectedValue == "1";
            phHeatingEstimate.Visible = rdoHeatingBills.SelectedValue == "0";
        }
    }

    void rdoHeatingBills_SelectedIndexChanged(object sender, EventArgs e)
    {
        phHeatingBills.Visible = rdoHeatingBills.SelectedValue == "1";
        phHeatingEstimate.Visible = rdoHeatingBills.SelectedValue == "0";
    }

    void ameeHeatingEstimate_LabelDataBound(object sender, CarbonExchange.WebControls.AmeeDrillDown.LabelDataBindingEventArgs e)
    {
        if (e.DataCatagory.ChoiceName == "homeDwellingType" || (e.DataCatagory.ChoiceName == "type" && e.DataCatagory.Selected.Where(x => x.Name == "state").Count() > 0))
        {
            //For "homeDwellingType" or "type" when address is american
            e.Label.Text = GetText("Home Type");
        }
        else if (e.DataCatagory.ChoiceName == "homeNoOfBedrooms" || e.DataCatagory.ChoiceName == "numberOfBedrooms")
        {
            e.Label.Text = GetText("No Bedrooms");
        }
        else if (e.DataCatagory.ChoiceName == "homeFuel" || e.DataCatagory.ChoiceName == "fuel")
        {
            e.Label.Text = GetText("Primary Heating Source");
        }
        else if (e.DataCatagory.ChoiceName == "homeAge")
        {
            e.Label.Text = GetText("Home Age");
        }
        else if (e.DataCatagory.ChoiceName == "type")
        {
            e.Label.Text = GetText("Heater Type");
        }
        else if (e.DataCatagory.ChoiceName == "state")
        {
            e.Label.Text = "State";
        }
    }

    void ameeHeatingEstimate_DropDownDataBinding(object sender, CarbonExchange.WebControls.AmeeDrillDown.DropDownDataBindingEventArgs e)
    {
        if (e.DataCatagory.ChoiceName == "homeFuel" || e.DataCatagory.ChoiceName == "fuel")
        {
            e.DataCatagory.Choices.Remove("electricity");
        }
    }

    void dsRenewable_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        CarbonExchange.Bll.AmeeDataCatagoryFactory factory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();
        var item = factory.GetByPath("home/energy/renewable", null);
        var choices = item.Choices;
        RenewableChoices = new List<string>(choices);
        RenewableChoiceName = item.ChoiceName;
        e.SetData(choices);
    }

    void rptRenewable_ItemDataBound(object sender, Acms.WebControls.ItemDataBoundEventArgs e)
    {
        var choice = e.DataItem as string;
        var cboRenewableItem = e.Item.FindControl("cboRenewableItem") as CheckBox;
        var txtRenewableItem = e.Item.FindControl("txtRenewableItem") as TextBox;
        if (cboRenewableItem != null && txtRenewableItem != null)
        {
            cboRenewableItem.Checked = Answer.GetSetting<bool>(string.Concat("cboRenewableItem_", choice));
            cboRenewableItem.Text = GetChoiceDisplayText(choice);
            txtRenewableItem.Text = Answer.GetSetting<string>(string.Concat("txtRenewableItem_", choice));
        }
    }

    void dsInsulation_Select(object sender, Acms.DataControls.EventDrivenDataSourceSelectEventArgs e)
    {
        CarbonExchange.Bll.AmeeDataCatagoryFactory factory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();
        var item = factory.GetByPath("/home/energy/insulation", null);
        var choices = item.Choices.Select(x => new { Text = GetChoiceDisplayText(x), Value = x });
        InsulationChoiceName = item.ChoiceName;
        e.SetData(choices);
    }

    void cblInsulation_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem item in cblInsulation.Items)
        {
            string settingName = string.Concat("cblInsulation_", item.Value);
            item.Selected = Answer.GetSetting<bool>(settingName);
        }
    }

    void ameeHeatingType_LabelDataBound(object sender, CarbonExchange.WebControls.AmeeDrillDown.LabelDataBindingEventArgs e)
    {
        if (e.DataCatagory.ChoiceName == "type")
        {
            e.Label.Text = GetText("Primary Heating Source");
        }
    }

    void ameeHeatingType_DropDownDataBinding(object sender, CarbonExchange.WebControls.AmeeDrillDown.DropDownDataBindingEventArgs e)
    {
        if (e.DataCatagory.ChoiceName == "type")
        {
            e.DataCatagory.Choices.Remove("electricity");
        }
    }

    public override void DataBind()
    {
        switch (Audit.Country.RegionInfo.TwoLetterISORegionName)
        {
            case "GB":
            case "IE":
                ameeHeatingEstimate.Path = "home/heating";
                break;
            case "US":
                ameeHeatingEstimate.Path = "home/heating/us";
                ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option(){Hidden = true, Choice=string.Format("State={0}", Audit.State), ChoiceText=Audit.State, Label="State"});
                break;
            case "CA":
                ameeHeatingEstimate.Path = "home/heating/us";
                ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=New York State", ChoiceText = "New York State", Label = "State" });
                break;
            case "AU":
                ameeHeatingEstimate.Path = "home/heating/us";
                ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=Georgia", ChoiceText = "Georgia", Label = "State" });
                break;
            case "CH":
                ameeHeatingEstimate.Path = "home/heating/us";
                ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=Colorado", ChoiceText = "Colorado", Label = "State" });
                break;
            case "HK":
                ameeHeatingEstimate.Path = "home/heating/us";
                ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=Florida", ChoiceText = "Florida", Label = "State" });
                break;
            case "JP":
                ameeHeatingEstimate.Path = "home/heating/us";
                ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=California", ChoiceText = "California", Label = "State" });
                break;
            case "AE":
                ameeHeatingEstimate.Path = "home/heating/us";
                ameeHeatingEstimate.AddOption(new CarbonExchange.WebControls.AmeeDrillDown.Option() { Hidden = true, Choice = "State=Hawaii", ChoiceText = "Hawaii", Label = "State" });
                break;
            default:
                ameeHeatingEstimate.Path = "home/heating";
                break;
        }

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rdoHeatingElectric")))
            rdoHeatingElectric.Text = Answer.GetSetting<string>("rdoHeatingElectric");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rdoHeatingBills")))
            rdoHeatingBills.Text = Answer.GetSetting<string>("rdoHeatingBills");

        ameeHeatingType.AddOptions(Answer.GetSetting<CarbonExchange.WebControls.AmeeDrillDown.Option[]>("ameeHeatingType"));

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("ddlHeatingPeriod")))
            ddlHeatingPeriod.Text = Answer.GetSetting<string>("ddlHeatingPeriod");

        txtHeatingValue.Text = Answer.GetSetting<string>("txtHeatingValue");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("ddlHeatingValueFormat")))
            ddlHeatingValueFormat.Text = Answer.GetSetting<string>("ddlHeatingValueFormat");

        //check the defaults havnt changed
        var tmpOptions = Answer.GetSetting<CarbonExchange.WebControls.AmeeDrillDown.Option[]>("ameeHeatingEstimate");
        var tmpPath = Answer.GetSetting<string>("ameeHeatingEstimatePath");
        if (tmpPath == ameeHeatingEstimate.Path && tmpOptions != null)
        {
            var existing = tmpOptions.Take(ameeHeatingEstimate.SelectedOptions.Count()).ToArray();
            var matching = true;
            for(var i = 0; i <existing.Count(); i++)
            {
                if (existing[i].Choice != ameeHeatingEstimate.SelectedOptions[i].Choice)
                {
                    matching = false;
                }
            }
            if (matching)
            {
                ameeHeatingEstimate.ClearOptions();
                ameeHeatingEstimate.AddOptions(tmpOptions);
            }
        }
        //fire selected index to show hide relevent options
        rdoHeatingElectric_SelectedIndexChanged(rdoHeatingElectric, EventArgs.Empty);
        rdoHeatingBills_SelectedIndexChanged(rdoHeatingBills, EventArgs.Empty);

        base.DataBind();
    }

    protected override bool SaveQuestion()
    {
        List<CarbonExchange.Bll.AnswerItem> itemsToKeep = new List<CarbonExchange.Bll.AnswerItem>();
        var completed = true;
        CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory = new CarbonExchange.Bll.AmeeProfileItemFactory();
        CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();


        Answer.SetSetting<string>("rdoHeatingElectric", rdoHeatingElectric.SelectedValue);
        if (rdoHeatingElectric.SelectedValue == "1")
        {
            //no need to save heating footprint
        }
        else if (rdoHeatingElectric.SelectedValue == "0")
        {
            Answer.SetSetting<string>("rdoHeatingBills", rdoHeatingBills.SelectedValue);
            if (rdoHeatingBills.SelectedValue == "1")
            {
                if (!SaveHeatingAmount(profileItemFactory, dataCategoryFactory, itemsToKeep))
                {
                    completed = false;
                }
            }
            else if (rdoHeatingBills.SelectedValue == "0")
            {
                if (!SaveHeatingEstimate(profileItemFactory, dataCategoryFactory, itemsToKeep))
                {
                    completed = false;
                }
            }
            else
            {
                completed = false;
            }
        }
        else
        {
            completed = false;
        }

        var deleteItems = Answer.AnswerItems.Where(x => !itemsToKeep.Contains(x)).ToList();

        if (deleteItems.Count > 0)
        {
            CarbonExchange.Bll.AnswerItemFactory answerItemFactory = new CarbonExchange.Bll.AnswerItemFactory();
            answerItemFactory.Delete(deleteItems);
            foreach (var del in deleteItems)
            {
                if (Answer.AnswerItems.Contains(del))
                    Answer.AnswerItems.Remove(del);
            }
        }
        return completed;
    }

    private bool SaveHeatingAmount(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        bool completed = true;

        Answer.SetSetting("ameeHeatingType", ameeHeatingType.SelectedOptions);
        Answer.SetSetting<string>("ddlHeatingPeriod", ddlHeatingPeriod.SelectedValue);
        Answer.SetSetting<string>("txtHeatingValue", txtHeatingValue.Text);
        Answer.SetSetting<string>("ddlHeatingValueFormat", ddlHeatingValueFormat.SelectedValue);

        string itemName = "HeatingBills";
        if (ameeHeatingType.CurrentCategory.DataItemSelected)
        {
            CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = EnsureProfileItem(itemName, profileItemFactory, ameeHeatingType.CurrentCategory);
            int months = 0;
            try
            {
                months = int.Parse(ddlHeatingPeriod.SelectedValue);
            }
            catch (FormatException)
            {
            }

            int amount = 0;
            try
            {
                amount = int.Parse(txtHeatingValue.Text);
            }
            catch (FormatException)
            {
            }

            decimal result = 0;
            if(months > 0)
            {
                result = (decimal)amount / (decimal)months;
            }

            bool save = false;
            foreach (ListItem option in ddlHeatingValueFormat.Items)
            {
                if (option.Selected)
                {
                    if (tmpProfileItem.GetValue<decimal>(option.Value) != result)
                    {
                        save = true;
                        tmpProfileItem.SetValue<decimal>(option.Value, result);
                    }
                }
                else
                {
                    if (tmpProfileItem.GetValue<decimal>(option.Value) != 0m)
                    {
                        save = true;
                        tmpProfileItem.SetValue<decimal>(option.Value, 0m);
                    }
                }
            }

            if (save)
            {
                profileItemFactory.Save(tmpProfileItem);
            }

            var tmpAnswerItem = Answer.SetItem(itemName, tmpProfileItem);
            itemsToKeep.Add(tmpAnswerItem);
            if(!(result > 0))
            {
                completed = false;
            }
        }
        else
        {
            Answer.SetItem(itemName, ameeHeatingType.CurrentCategory);
            completed = false;
        }

        return completed;
    }

    private bool SaveHeatingEstimate(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        bool completed = true;
        //Save heating Estimate
        Answer.SetSetting<CarbonExchange.WebControls.AmeeDrillDown.Option[]>("ameeHeatingEstimate", ameeHeatingEstimate.SelectedOptions);
        Answer.SetSetting<string>("ameeHeatingEstimatePath", ameeHeatingEstimate.Path);
        string itemName = "HeatingEstimate";

        if (ameeHeatingEstimate.CurrentCategory.DataItemSelected)
        {
            CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = EnsureProfileItem(itemName, profileItemFactory, ameeHeatingEstimate.CurrentCategory);
            if (string.IsNullOrEmpty(tmpProfileItem.Id))
            {
                profileItemFactory.Save(tmpProfileItem);
            }
            itemsToKeep.Add(Answer.SetItem(itemName, tmpProfileItem));
        }
        else
        {
            completed = false;
            itemsToKeep.Add(Answer.SetItem(itemName, ameeHeatingEstimate.CurrentCategory));
        }

        //save each renewable checked
        int i = 0;
        foreach (var item in rptRenewable.Items)
        {
            string choice = RenewableChoices[i];
            CheckBox cboRenewableItem = item.FindControl("cboRenewableItem") as CheckBox;
            TextBox txtRenewableItem = item.FindControl("txtRenewableItem") as TextBox;
            if (cboRenewableItem != null && txtRenewableItem != null)
            {
                Answer.SetSetting(string.Concat("cboRenewableItem_", choice), cboRenewableItem.Checked);
                Answer.SetSetting(string.Concat("txtRenewableItem_", choice), txtRenewableItem.Text);
                if (cboRenewableItem.Checked)
                {
                    string reneweableItemName = string.Concat("RenewableItem_", choice);
                    string path = "home/energy/renewable";
                    CarbonExchange.Bll.AmeeProfileItem tmpProfileItem = EnsureProfileItem(reneweableItemName, profileItemFactory, dataCategoryFactory, path, string.Format("{0}={1}", RenewableChoiceName, choice));

                    decimal val = 0;
                    try
                    {
                        val = decimal.Parse(txtRenewableItem.Text);
                    }
                    catch (FormatException)
                    {
                    }

                    bool save = string.IsNullOrEmpty(tmpProfileItem.Id);
                    if (tmpProfileItem.GetValue<decimal>("kWhGeneratedPerMonth") != val)
                    {
                        tmpProfileItem.SetValue<decimal>("kWhGeneratedPerMonth", val);
                        save = true;
                    }

                    if (save)
                    {
                        profileItemFactory.Save(tmpProfileItem);
                    }

                    itemsToKeep.Add(Answer.SetItem(reneweableItemName, tmpProfileItem));
                }
            }
            i++;
        }

        foreach (ListItem item in cblInsulation.Items)
        {
            if (item.Selected)
            {
                string settingName = string.Concat("cblInsulation_", item.Value);
                string insulationName = string.Concat("Insulation_", item.Value);
                Answer.SetSetting(settingName, item.Selected);
                var tmpAmeeInsulationItem = EnsureProfileItem(insulationName, profileItemFactory, dataCategoryFactory, "/home/energy/insulation", string.Format("{0}={1}", InsulationChoiceName, item.Value));
                if (string.IsNullOrEmpty(tmpAmeeInsulationItem.Id))
                {
                    profileItemFactory.Save(tmpAmeeInsulationItem);
                }
                itemsToKeep.Add(Answer.SetItem(insulationName, tmpAmeeInsulationItem));
            }
        }
        return completed;
    }

    protected override object SaveViewState()
    {
        ViewState["RenewableChoices"] = RenewableChoices;
        ViewState["RenewableChoiceName"] = RenewableChoiceName;
        ViewState["InsulationChoiceName"] = InsulationChoiceName;
        return base.SaveViewState();
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        RenewableChoices = ViewState["RenewableChoices"] as List<string>;
        RenewableChoiceName = ViewState["RenewableChoiceName"] as string;
        InsulationChoiceName = ViewState["InsulationChoiceName"] as string;
    }

    public override int GetActiveItemsCount()
    {
        int i = 1;

        if (pnlHeatingBills.Visible)
            i++;

        if (phHeatingBills.Visible)
            i += phHeatingBills.Controls.Count;
        else if (phHeatingEstimate.Visible)
            i += phHeatingEstimate.Controls.Count;


        return i;
    }

    public override int RenderItems(int start, int end, HtmlTextWriter writer)
    {
        throw new NotImplementedException();
    }

}
